<?php

namespace App\Http\Controllers\Home;

use App\Models\Articles;
use App\Models\Collections;
use App\Models\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class NewsController extends Controller
{
    /**
     * 新闻列表页面
     * @param url home.news.news
     * @param Request $request
     * @return bool
     */
    public function news(){
        $title = '新闻列表';
        return view('home.news.newslist',compact('title'));
    }

    /**
     * 新闻列表
     * @param url home.news.newsList
     * @param Request $request
     * @param sid 排序id 默认:发布时间 1:浏览量 2:收藏量
     * @param keyword 热搜词条
     * @param orderby 1:倒叙 2:正序
     * @return bool
     */
    public function newsList(Request $request){
        try{
            $params = [
                'keyword' => (string)$request->get('keyword')//热搜词条
            ];
            $page = (int)$request->get('page',1);//页码
            $sid = (int)$request->get('sid');//排序
            $orderby = (string)$request->get('orderby','desc');//排序
            if ($sid == 1){
                $sort = 'view';
            }elseif ($sid == 2){
                $sort = 'collect';
            }else{
                $sort = 'created_at';
            }
            $fields = ['id','thumb','title','content','view','collect','created_at'];
            $lists = Articles::allLists($params,$fields,$page,10,$sort,$orderby);
            foreach ($lists as $key=>$val){
                $lists[$key]['content'] = str_limit(strip_tags($val['content']) , 170 , '...' );//str_limit 字符截取 strip_tags 去除HTML标签
                $lists[$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                $lists[$key]['collect'] = strlen($val['collect'])>=4 ? '999+' : $val['collect'];
            }
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 各类新闻
     * @param url home.news.newsCate
     * @param Request $request
     * @return bool
     * @return hot:热门 new:最新
     */
    public function newsCate(){
        try{
            $lists['hot'] = Articles::allLists(['hot'=>2], ['id','title','view'], null, 10,'view');
            $lists['new'] = Articles::allLists([], ['id','title','view'], null, 10,'created_at');
            foreach ($lists['hot'] as $key=>$val){
                $lists['hot'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
            }
            foreach ($lists['new'] as $key=>$val){
                $lists['new'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
            }
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 新闻详情页面
     * @param url home.news.newsDetails
     * @param Request $request
     * @return bool
     */
    public function newsDetails(){

        $title = '新闻列表';
        return view('home.news.newsDetails',compact('title'));
    }

    /**
     * 新闻详情
     * @param url home.news.detailsApi
     * @param Request $request
     * @param id 新闻id
     * @return bool
     * @return source 来源
     * @return collect 收藏量
     * @return is_collect 当前用户是否收藏：1未收藏，2已收藏
     */
    public function detailsApi(Request $request){
        try{
            $id = (int)$request->get('id');//新闻id
            if (empty($id)) return $this->writeJson(1,route('home.news.newsList'),'参数错误');
            $lists = Articles::details(['id'=>$id]);
            $lists['view'] = strlen($lists['view'])>=4 ? '999+' : $lists['view'];
            $lists['collect'] = strlen($lists['collect'])>=4 ? '999+' : $lists['collect'];
            $lists['is_collect'] = 1;//默认未收藏
            $userinfo = auth()->guard('web')->user();//获取当前登录用户
            if (!empty($userinfo) && $userinfo['type'] == 1){
                $collect = Collections::where(['collect_id'=>$id,'user_id'=>$userinfo['id'],'type'=>2])->value('collect_id');
                $lists['is_collect'] = empty($collect) ? 1 : 2;
            }
            Articles::where('id',$id)->increment('view');//浏览量加1
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 收藏
     * @param url home.news.newsCollect
     * @param Request $request
     * @param collect_id 收藏内容id
     * @return bool
     */
    public function newsCollect(Request $request){
        try{
            $user_id = auth()->guard('web')->id();
            if (empty($user_id)) return response()->json($data = ["code"=>300,"data"=>null,"msg"=>'请先登录'], $status = 307);
            $collect_id = (int)$request->post('collect_id');
            if (empty($collect_id)) return $this->writeJson(1,null,'参数错误');
            $userinfo = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['type','status']);
            if (empty($userinfo)){
                return $this->writeJson(1,null,'用户不存在,请联系客服!');
            }else{
                if($userinfo['status'] == 2){
                    return $this->writeJson(1, null,'账户正在审核中，请等待审核!');
                }elseif($userinfo['status'] == 3){
                    return $this->writeJson(1, null,'账号未通过审核，请前往个人中心查看原因并重新提交审核!');
                }elseif ($userinfo['status'] == 4){
                    return $this->writeJson(1, null,'账号已锁定，请前往个人中心查看原因或联系客服!');
                }
                if ($userinfo['type'] != 1) return $this->writeJson(1,null,'供应商不能收藏!');
            }

            $collect = Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>2])->value('id');
            if (empty($collect)){
                $params = [
                    'collect_id' => $collect_id,
                    'user_id' => $user_id,
                    'collect_at' => date('Y-m-d H:i:s'),
                    'type' => 2,
                ];
                Collections::create($params);
                Articles::where('id',$collect_id)->increment('collect');
                return $this->writeJson(0, null, '收藏成功');
            }else {
                Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>2])->delete();
                return $this->writeJson(0, null, '取消收藏成功');
            }
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }


}